package cn.cloud9.designpattern.dp01singleton;

/**
 * @author OnCloud9
 * @description 懒汉式第一种
 * @project Java
 * @date 2022年05月22日 9:56
 */
public class Singleton3 {

    private Singleton3(){}

    private static Singleton3 instance;

    /**
     * 如果instance为空 就new出来，反之直接返回
     * 多线程情况会存在判断失效问题
     * @return
     */
    public static Singleton3 getInstance(){
        if (instance == null) instance = new Singleton3();
        return instance;
    }

    public static void main(String[] args) {
        class Test implements Runnable {
            @Override
            public void run() {
                final Singleton3 instance = Singleton3.getInstance();
                System.out.println(Thread.currentThread().getName() + " -> " + instance);
            }
        }

        final Thread thread1 = new Thread(new Test());
        final Thread thread2 = new Thread(new Test());

        thread1.start();
        thread2.start();
        System.out.println(" end ");
        /*
        * 需要多执行几次会出现这种情况，判断不稳定
        *  end
        * Thread-0 -> cn.cloud9.designpattern.dp01singleton.Singleton3@1f38108d
        * Thread-1 -> cn.cloud9.designpattern.dp01singleton.Singleton3@5abea0a2
        * */
    }
}
